package com.weixingtu.commuterCar.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import net.sf.json.JSONObject;

import com.weixingtu.commuterCar.util.AuthUtil;


@WebServlet(urlPatterns = "/loginCallback")
public class LoginIdVerifServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获取code
        String code = request.getParameter("code");

        //获取access_token
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + AuthUtil.CORPID + "&corpsecret=" + AuthUtil.APPSECRET;
        //通过网络请求方法来请求上面这个接口
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        //从返回的JSON数据中取出access_token
        String token = jsonObject.getString("access_token");

        //刷新access_token?


        //拉取用户信息
        String infoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + token + "&code=" + code;
        //通过网络请求方法来请求上面这个接口
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
/*
        if(jsonObject.containsKey("UserId")){  //判断是否有这一键名。若有：
            String userId = jsonObject.getString("UserId");

            //设置cookie
            Cookie cookie = new Cookie("userId", userId);
            cookie.setMaxAge(7200); //设置cookie过期时间为两小时
//            cookie.setDomain();  设置域名
            response.addCookie(cookie); //保存cookie到客户端

        }else{  //若无：
//            用户不为企业人员，无法访问本网站
        }
*/
        request.setAttribute("userInfo", userInfo);

        if (userInfo.has("UserId")){
            String userId = userInfo.getString("UserId");
            request.setAttribute("userId", userId);
        }else if (userInfo.has("OpenId")){
            String openId = userInfo.getString("OpenId");
            request.setAttribute("openId", openId);
        }else {
            request.getRequestDispatcher("/index.jsp");
        }
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    }
}
